<template>
  <div class='main-box'>
    <canvas ref='canvas'></canvas>
    <a-button type='primary'
              size="mini"
              style='margin: 0 auto;' @click='download'>
      保存二维码
    </a-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import QRCode from 'qrcode';

const props = defineProps({
  url: {
    type: String,
    required: true
  },
  width: {
    type: String,
    required: false,
    default: 100
  },
  height: {
    type: String,
    required: false,
    default: 100
  }
});
const canvas = ref();
const createQrCode = () => {
  QRCode.toCanvas(canvas.value, props.url, { width: props.width, height: props.height });
};
const download = () => {
  let a = document.createElement('a');
  a.href = canvas.value.toDataURL('image/png');
  a.download = '二维码';
  a.click();
};
onMounted(() => {
  createQrCode();
});
</script>

<style scoped>
.main-box {
  width: 100px;
  display: flex;
  flex-direction: column;
}

.qr-code {
  cursor: pointer !important;
}

.qr-code:hover {
  opacity: .5;
}
</style>
